<route lang="json5" type="page">
{
	style: {
		navigationStyle: 'custom',
		navigationBarTitleText: '专家荐书',
	},
}
</route>

<template>
	<view class="page-bookrack">
		<fly-navbar backgroundColor="#ffffff" leftText="专家荐书" fixed />
		<view class="w-full box-border">
			<view class="w-full h-[110rpx] px-4 pb-[13rpx] flex items-end justify-between box-border">
				<view class="flex items-center h-[63rpx]">
					<view
						class="px-3 h-full flex justify-center items-center rounded-[30rpx] text-[#303030] text-[26rpx] mr-2"
						style="background: #f3f3f5"
						@tap="openModal('classify', '选择图书分类')"
						>{{ query.classify_name }} <text class="triangle"></text
					></view>
					<view
						class="px-3 h-full flex justify-center items-center rounded-[30rpx] text-[#303030] text-[26rpx]"
						style="background: #f3f3f5"
						@tap="openModal('grade', '选择年级')"
						>{{ query.grade_name }}<text class="triangle"></text
					></view>
				</view>
				<view
					class="w-[63rpx] h-[63rpx] flex justify-center items-center rounded-[50%]"
					style="background: #f3f3f5"
					@tap="linkUrl('/pages-book/search/index')"
				>
					<image :src="baseImg + '/book/book-search.png'" class="w-[30rpx] h-[30rpx]"></image>
				</view>
			</view>
			<scroll-view
				class="w-full"
				:style="{ height: contentHeight - 110 + 'rpx' }"
				scroll-y
				v-if="thisPage === 1 && bookList.length"
				@scrolltolower="scrolltolower"
			>
				<view class="w-full px-4 py-4 box-border">
					<view class="w-full box-border rounded-[30rpx] recommend-box">
						<view
							v-for="item in bookList"
							:key="item.id"
							@tap="toBook(item.id)"
							class="mb-4 last:mb-0"
						>
							<book-item :item="item" @receive="receive"></book-item>
						</view>
					</view>
				</view>
			</scroll-view>
			<no-page
				v-if="thisPage === 0 || (thisPage === 1 && !bookList.length)"
				height="100%"
				:type="thisPage === 0 ? 'btn' : 'msg'"
				:title="title"
				@click="retry"
			></no-page>
		</view>
		<uni-popup ref="popup" :mask-click="false" type="bottom" background-color="transparent">
			<view class="w-full h-[824rpx] px-6 py-4 box-border">
				<view
					class="w-full bg-white h-full rounded-[30rpx] py-6 box-border flex flex-col justify-center"
				>
					<view class="w-full h-[53rpx] flex justify-between items-center px-6 box-border">
						<image
							@tap="closeModal"
							:src="baseImg + '/close-btn.png'"
							class="w-[44rpx] h-[44rpx]"
						></image>
						<text class="text-[#303030] text-[44rpx]">{{ modalInfo.title }}</text>
						<view
							class="text-[#fff] text-[29rpx] rounded-[29rpx] h-[53rpx] flex px-4 justify-center items-center"
							style="background: #2ba5e0"
							@tap="confirm"
							>确认</view
						>
					</view>
					<view class="w-full pt-6 box-border" style="height: calc(100% - 53rpx)">
						<view class="h-full flex justify-between py-2 box-border">
							<scroll-view scroll-y class="w-full h-full">
								<view
									v-for="item in modalList"
									:key="item.id"
									@tap="setItem(item.id, item.name)"
									class="w-full flex justify-center items-center mb-2 last:mb-0"
								>
									<view
										class="max-w-full px-[38rpx] h-[54rpx] box-border flex justify-center items-center rounded-[27rpx] text-[#303030] text-[29rpx]"
										:style="{
											background: modalInfo.id == item.id ? '#44C651' : '',
											color: modalInfo.id == item.id ? '#fff' : '#303030',
										}"
										><text class="truncate">{{ item.name }}</text></view
									>
								</view>
							</scroll-view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store';
import { getRecommendBookList, getRecommendClassifyGrade } from '@/service/book';
import { systemInfo } from '@/utils/getSystemInfo';
import { getReceivePoint } from '@/service/user';
import { initializeApp } from '@/utils';
import { toAuthPage } from '@/utils/jump';
import onShare from '@/hooks/useShare';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { onShareAppMessage, onShareTimeline } = onShare();
const { contentHeight } = systemInfo();
const baseImg = ref(import.meta.env.VITE_STATIC_IMAGE);
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const bookList = ref([]);
const title = ref('');
const thisPage = ref(-1);
const page = ref({ number: 1, size: 10 });
const hasMore = ref(true);
const popup = ref(null);
const classifyList = ref([]);
const gradeList = ref([]);
const query = ref({
	classify_id: 0,
	grade_id: 0,
	grade_name: '全部',
	classify_name: '全部',
});
const modalList = ref([]);
const modalInfo = ref({
	id: 0,
	type: '',
	name: '',
	title: '',
});

onLoad(options => {
	// classify_id: 分类ID
	if (options.classify_id) {
		query.value = {
			...query.value,
			classify_id: Number(options.classify_id),
		};
	}
});

onShow(() => {
	initializeApp(getList(), getClassifyGrade());
});

const linkUrl = (url: string) => {
	uni.navigateTo({
		url,
	});
};

const closeModal = () => {
	modalInfo.value = {
		id: 0,
		type: '',
		name: '',
		title: '',
	};
	popup.value?.close();
};

const scrolltolower = () => {
	if (!hasMore.value) return;
	page.value.number++;
	getList();
};

const getClassifyGrade = async () => {
	const res = await getRecommendClassifyGrade();
	if (res.status_code === 200) {
		classifyList.value = res.data.book_classify;
		if (res.data.book_classify?.length && query.value.classify_id) {
			const obj = res.data.book_classify.find(item => item.id === query.value.classify_id);
			if (obj) {
				query.value.classify_name = obj.name;
			}
		}
		if (res.data.grade_list.length) {
			gradeList.value = res.data.grade_list.map(item => {
				return {
					id: item.grade_id,
					name: item.grade_name,
				};
			});
		}
	}
};

const getList = async () => {
	uni.showLoading({ title: '加载中...' });
	try {
		const res = await getRecommendBookList({
			page: page.value.number,
			page_size: page.value.size,
			classify_id: query.value.classify_id,
			grade_id: query.value.grade_id,
			student_id: userInfo.value.student_id,
		});
		uni.hideLoading();
		if (res.status_code === 200 && res.data) {
			thisPage.value = 1;
			bookList.value =
				page.value.number === 1 ? res.data.book_list : [...bookList.value, ...res.data.book_list];
			if (res.data.book_list.length < page.value.size) {
				hasMore.value = false;
			}
			if (!bookList.value.length) {
				title.value = '暂无数据';
			}
		} else {
			thisPage.value = 0;
			title.value = res.message;
		}
	} catch (error) {
		uni.hideLoading();
		thisPage.value = 0;
		title.value = '服务器异常';
	}
};

const retry = () => {
	hasMore.value = true;
	page.value = { number: 1, size: 10 };
	getList();
};

const toBook = (id: number) => {
	if (id === undefined) return;
	if (!userInfo.value.student_id) {
		toAuthPage({}, { type: 'navigateTo', url: `/pages-book/details/index?id=${id}` });
	} else {
		uni.navigateTo({
			url: `/pages-book/details/index?id=${id}`,
		});
	}
};

const openModal = (type?, title?) => {
	modalInfo.value.type = type;
	modalInfo.value.title = title;
	let id = 0;
	let name = '';
	let list = [];
	if (type === 'grade') {
		id = query.value.grade_id;
		name = query.value.grade_name;
		list = gradeList.value;
	}
	if (type === 'classify') {
		id = query.value.classify_id;
		name = query.value.classify_name;
		list = classifyList.value;
	}
	modalList.value = [{ id: 0, name: '全部' }, ...list];
	modalInfo.value.id = id;
	modalInfo.value.name = name;
	popup.value?.open();
};

const setItem = (id, name) => {
	modalInfo.value.id = id;
	modalInfo.value.name = name;
};

const confirm = () => {
	const { type } = modalInfo.value;
	if (type === 'classify') {
		query.value.classify_id = modalInfo.value.id;
		query.value.classify_name = modalInfo.value.name;
	}
	if (type === 'grade') {
		query.value.grade_id = modalInfo.value.id;
		query.value.grade_name = modalInfo.value.name;
	}
	hasMore.value = true;
	page.value.number = 1;
	getList();
	closeModal();
};

const receive = async item => {
	uni.showLoading({
		title: '领取中...',
	});
	try {
		const res = await getReceivePoint({
			student_id: userInfo.value.student_id,
			book_id: item.id,
		});
		uni.hideLoading();
		if (res.status_code === 200) {
			uni.showToast({
				icon: 'none',
				title: '领取成功',
				success: () => {
					retry();
				},
			});
		} else {
			uni.showToast({
				icon: 'none',
				title: res.message,
			});
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '领取失败,请重试',
		});
	}
};
</script>

<style lang="scss">
page {
	background: #fff;
}
</style>
<style lang="scss" scoped>
.page-bookrack {
	width: 100%;
	height: 100vh;
	background: #fff;
}

.destroy::after {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	width: 75rpx;
	height: 55rpx;
	color: #919191;
	content: 'x';
	background: #e8e8e8;
	border-radius: 27rpx 0 0 27rpx;
}

.recommend-box {
	box-shadow:
		0rpx 3rpx 4rpx 0rpx rgb(0 0 0 / 2%),
		0rpx 5rpx 45rpx 0rpx rgb(0 0 0 / 10%);
}

.triangle {
	width: 0;
	height: 0;
	margin-left: 11rpx;
	border-top: 15rpx solid #777;
	border-right: 10rpx solid transparent;
	border-left: 10rpx solid transparent;
}
</style>
